package com.shop.config;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.constan.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

@Configuration
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断路径
        String path = exchange.getRequest().getURI().getPath();
        if (GatewayConstant.ALLOW_URL.contains(path)) {
            //放
            return chain.filter(exchange);
        }
        //2.token校验
        List<String> tokenList = exchange.getRequest().getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(tokenList)) {
            String token = tokenList.get(0);
            if (!StringUtils.isEmpty(token)) {
                //截取
                String jwt = token.replaceAll("bearer", "");
                if (!StringUtils.isEmpty(jwt)) {
                    //保存redis,加多个key前缀
                    Boolean hasKey = redisTemplate.hasKey(GatewayConstant.JWT_PREFIX + jwt);
                    if (hasKey) {
                        //放
                        return chain.filter(exchange);
                    }
                }
            }
        }
        //没有就返回401给前端
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        //objectMapper写出去
        HashMap<String, Object> date = new HashMap<>(4);
        date.put("code", 401);
        date.put("msg", "未授权");

        ObjectMapper objectMapper = new ObjectMapper();

        byte[] b = new byte[0];
        //转字节
        try {
            b = objectMapper.writeValueAsBytes(date);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //通过buffer写出去
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(b);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
